
#include "util/logger.hxx"
#include <stdarg.h>

Logger* Logger::m_instance = NULL;

DbStatus Logger::open() {
    
    DbStatus ret;

    m_file = fopen(m_fname.c_str(), "a");
    if(m_file == NULL) ret = DbStatus(m_fname, errno);

    return ret;
}

DbStatus Logger::init(const std::string& logFileName) {
    
    DbStatus ret;

    m_instance = new Logger(logFileName);
    ret = m_instance->open();

    return ret;
}

void Logger::log(const char* format, ...) {
    
    if(m_instance == NULL) return;

    va_list va;
    va_start(va, format);
    m_instance->DbLog(format, va);
    va_end(va);
}

void Logger::DbLog(const char* format, va_list va) {
    
    pid_t pid = getpid();;

    char buf[2048];
    char* p = buf;

    struct timeval now;
    gettimeofday(&now, NULL);
    struct tm t;
    localtime_r(&now.tv_sec, &t);
    p += snprintf(p, buf + sizeof(buf) - p,
            "%04d/%02d/%02d-%02d:%02d:%02d.%06d %d ",
            t.tm_year + 1900,
            t.tm_mon + 1,
            t.tm_mday,
            t.tm_hour,
            t.tm_min,
            t.tm_sec,
            now.tv_usec,
            pid);

    p += vsnprintf(p, buf + sizeof(buf) - 1 - p, format, va);


    if (p[-1] != '\n') {
        *p++ = '\n';
    }

    fwrite(buf, 1, p - buf, m_file);
    fflush(m_file);
}

